package org.example.leetcode.core.pachong;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.leetcode.core.dao.TQuestionMapper;
import org.example.leetcode.core.dao.TQuestionTypeMapper;
import org.example.leetcode.core.domain.TQuestion;
import org.example.leetcode.core.domain.TQuestionType;
import org.example.leetcode.core.service.TQuestionService;
import org.example.leetcode.core.service.impl.TQuestionServiceImpl;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PaChong {
    public static String cookie="gr_user_id=06a41d42-fea3-4187-b753-459f2069fff7; _bl_uid=C6ljyng0hw75OvmpIqbRmOvnh8kk; csrftoken=XsYzjRWHwVEAKx4FIX37Hlr4DjcJvrwUOAeqGawUyUILTEw7IzDIoEUj8GRRtRWg; a2873925c34ecbd2_gr_last_sent_cs1=heng-xing-da-lian-mao; Hm_lvt_fa218a3ff7179639febdb15e372f411c=1704379054,1704552040; tfstk=eRMMj1vEifPsVSBSvVe6ptxf5yALCNwblqBYk-U2TyzQHfK_kr0mP4VqBmeanr0qR1FYkP3Hm2uSXSeZnX6mVmM9f-K_Ccwb3ULJeqmsf-M1YKvMeCAN_Y8JyLpKD2nvUUhTR-NPY98pQvWSnhVurgbekgfpb1gSbyXoAvqZ31iT-CAsKcFgzd4h3tk3jgkAT_5WktZeDv5fG5rQxzIdhqQ7XnB6JHxhanNaAlaJxHffG5rQxzKHx_Jb_kZ_y; _gid=GA1.2.1853247169.1709044361; Hm_lvt_f0faad39bcf8471e3ab3ef70125152c3=1708764279,1708862989,1709044361,1709101620; LEETCODE_SESSION=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuZXh0X2FmdGVyX29hdXRoIjoiLyIsIl9hdXRoX3VzZXJfaWQiOiI1MDYxMTE1IiwiX2F1dGhfdXNlcl9iYWNrZW5kIjoiZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmQiLCJfYXV0aF91c2VyX2hhc2giOiIzNDcwNWQ1NzI3OTZhMzU5ZTQwYzU5MDI4MTYyOTk0Mjg5NTJjZWM2N2ZhOTg5MGNhNzU5Y2YxNjBiMTQ5ZjMwIiwiaWQiOjUwNjExMTUsImVtYWlsIjoidG9wdG9wMTIzNDVAMTYzLmNvbSIsInVzZXJuYW1lIjoiaGVuZy14aW5nLWRhLWxpYW4tbWFvIiwidXNlcl9zbHVnIjoiaGVuZy14aW5nLWRhLWxpYW4tbWFvIiwiYXZhdGFyIjoiaHR0cHM6Ly9hc3NldHMubGVldGNvZGUuY24vYWxpeXVuLWxjLXVwbG9hZC91c2Vycy9oZW5nLXhpbmctZGEtbGlhbi1tYW8vYXZhdGFyXzE2NTczNDQ4NTUucG5nIiwicGhvbmVfdmVyaWZpZWQiOnRydWUsIl90aW1lc3RhbXAiOjE3MDgzNDY1MDEuNzQ0MzQxLCJleHBpcmVkX3RpbWVfIjoxNzEwODc0ODAwLCJ2ZXJzaW9uX2tleV8iOjAsImxhdGVzdF90aW1lc3RhbXBfIjoxNzA5MTA1NDc3fQ.QgJ9tPDACpHVmxNBwZcY-kWcXgBmbOB7I00MMl1Wls8; a2873925c34ecbd2_gr_session_id=54fc05f6-cb2a-4dac-b342-2c043798e3a3; a2873925c34ecbd2_gr_last_sent_sid_with_cs1=54fc05f6-cb2a-4dac-b342-2c043798e3a3; a2873925c34ecbd2_gr_session_id_sent_vst=54fc05f6-cb2a-4dac-b342-2c043798e3a3; Hm_lpvt_f0faad39bcf8471e3ab3ef70125152c3=1709112164; _ga=GA1.1.1639696937.1676285818; a2873925c34ecbd2_gr_cs1=heng-xing-da-lian-mao; _ga_PDVPZYN3CW=GS1.1.1709112159.100.1.1709113962.60.0.0";
    public static String data="{\n" +
            "    \"query\": \"\\n    query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {\\n  problemsetQuestionList(\\n    categorySlug: $categorySlug\\n    limit: $limit\\n    skip: $skip\\n    filters: $filters\\n  ) {\\n    hasMore\\n    total\\n    questions {\\n      acRate\\n      difficulty\\n      freqBar\\n      frontendQuestionId\\n      isFavor\\n      paidOnly\\n      solutionNum\\n      status\\n      title\\n      titleCn\\n      titleSlug\\n      topicTags {\\n        name\\n        nameTranslated\\n        id\\n        slug\\n      }\\n      extra {\\n        hasVideoSolution\\n        topCompanyTags {\\n          imgUrl\\n          slug\\n          numSubscribed\\n        }\\n      }\\n    }\\n  }\\n}\\n    \",\n" +
            "    \"variables\": {\n" +
            "        \"categorySlug\": \"all-code-essentials\",\n" +
            "        \"skip\": 0,\n" +
            "        \"limit\": 10,\n" +
            "        \"filters\": {}\n" +
            "    },\n" +
            "    \"operationName\": \"problemsetQuestionList\"\n" +
            "}";
    public static String data2="{\n" +
            "\t\"query\": \"\\n    query questionTranslations($titleSlug: String!) {\\n  question(titleSlug: $titleSlug) {\\n    translatedTitle\\n    translatedContent\\n  }\\n}\\n    \",\n" +
            "\t\"variables\": {\n" +
            "\t\t\"titleSlug\": \"two-sum\"\n" +
            "\t},\n" +
            "\t\"operationName\": \"questionTranslations\"\n" +
            "}";
    public static String generatePageRequest(int skip,int limit){
        return "{\n" +
                "    \"query\": \"\\n    query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {\\n  problemsetQuestionList(\\n    categorySlug: $categorySlug\\n    limit: $limit\\n    skip: $skip\\n    filters: $filters\\n  ) {\\n    hasMore\\n    total\\n    questions {\\n      acRate\\n      difficulty\\n      freqBar\\n      frontendQuestionId\\n      isFavor\\n      paidOnly\\n      solutionNum\\n      status\\n      title\\n      titleCn\\n      titleSlug\\n      topicTags {\\n        name\\n        nameTranslated\\n        id\\n        slug\\n      }\\n      extra {\\n        hasVideoSolution\\n        topCompanyTags {\\n          imgUrl\\n          slug\\n          numSubscribed\\n        }\\n      }\\n    }\\n  }\\n}\\n    \",\n" +
                "    \"variables\": {\n" +
                "        \"categorySlug\": \"all-code-essentials\",\n" +
                "        \"skip\": "+skip+",\n" +
                "        \"limit\": "+limit+",\n" +
                "        \"filters\": {}\n" +
                "    },\n" +
                "    \"operationName\": \"problemsetQuestionList\"\n" +
                "}";
    }
    public static String generateSpecificDescriptionRequest(String slug){
        return "{\n" +
                "\t\"query\": \"\\n    query questionTranslations($titleSlug: String!) {\\n  question(titleSlug: $titleSlug) {\\n    translatedTitle\\n    translatedContent\\n  }\\n}\\n    \",\n" +
                "\t\"variables\": {\n" +
                "\t\t\"titleSlug\": \""+slug+"\"\n" +
                "\t},\n" +
                "\t\"operationName\": \"questionTranslations\"\n" +
                "}";
    }
    public static void main(String[] args) throws IOException {
        for(int i=0;i<3450;i+=50){
            System.out.println(i);
            getQuestion(i,50);
        }
    }
    public static String getSpecificQuestionDescription(String titleSlug) throws IOException {
        try {
            // 构造 URL 对象
            URL url = new URL("https://leetcode.cn/graphql/");

            // 打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Cookie",cookie);

            // 设置是否向 URL 连接输出，因为这个是 POST 请求，参数要放在 http 正文内
            connection.setDoOutput(true);

            // 构造请求体
            String requestBody = generateSpecificDescriptionRequest(titleSlug);

            // 将请求体写入 HTTP 正文
            OutputStream os = connection.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();
            os.close();

            // 获取返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"ISO-8859-1"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            String data =new String(response.toString().getBytes(),"UTF-8");
            PaChongData question = JSONObject.parseObject(data, PaChongData.class);
            return question.getData().getQuestion().getTranslatedContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
    }
    public static void getQuestion(int skip,int limit){
        try {
            // 构造 URL 对象
            URL url = new URL("https://leetcode.cn/graphql/");

            // 打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            // 设置是否向 URL 连接输出，因为这个是 POST 请求，参数要放在 http 正文内
            connection.setDoOutput(true);

            // 构造请求体
            String requestBody = generatePageRequest(skip,limit);

            // 将请求体写入 HTTP 正文
            OutputStream os = connection.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();
            os.close();

            // 获取返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            String res=response.toString();
            PaChongData paChongData = JSONObject.parseObject(res, PaChongData.class);
            ProblemSetQuestionList problemsetQuestionList = paChongData.getData().getProblemsetQuestionList();
            TQuestionService tQuestionService=new TQuestionServiceImpl();
            String resource = "Mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            TQuestionMapper tQuestionMapper = sqlSession.getMapper(TQuestionMapper.class);
            TQuestionTypeMapper tQuestionTypeMapper = sqlSession.getMapper(TQuestionTypeMapper.class);
            Map<String,String> map=new HashMap<>();
            for (Question question : problemsetQuestionList.getQuestions()) {
                if(tQuestionMapper.selectCountByName(question.getTitleCn())!=0){
                    continue;
                }
                TQuestion tQuestion = new TQuestion();
                BeanUtils.copyProperties(question,tQuestion);
                tQuestion.setTitle(question.getTitleCn());
                tQuestion.setPayOnly(question.getPaidOnly()?"Y":"N");
                List<String> types=new ArrayList<>();
                for (TopicTag topicTag : question.getTopicTags()) {
                    if(map.containsKey(topicTag.getName())){
                        types.add(map.get(topicTag.getName()));
                    }
                    else{
                        //去数据库里查有没有这个type，没有新增type,并把id返回存在Map里
                        TQuestionType tQuestionType = tQuestionTypeMapper.selectByName(topicTag.getName());
                        if(tQuestionType==null){
                            TQuestionType newQuestionType = new TQuestionType();
                            newQuestionType.setCode(topicTag.getName());
                            newQuestionType.setName(topicTag.getNameTranslated());
                            tQuestionTypeMapper.insertNewType(newQuestionType);
                            map.put(topicTag.getName(),newQuestionType.getId()+"");
                            types.add(newQuestionType.getId()+"");
                        }
                        else{
                            types.add(tQuestionType.getId()+"");
                            map.put(topicTag.getName(),tQuestionType.getId()+"");
                        }
                    }
                }
                String s = types.toString();
                tQuestion.setType(s.substring(1,s.length()-1));
                tQuestion.setDescription(getSpecificQuestionDescription(tQuestion.getTitleSlug()));
                tQuestionMapper.insertT(tQuestion);
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
